package com.hand.wfive.activity.edit

import android.annotation.SuppressLint
import android.content.Context
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.SimpleItemAnimator
import com.alibaba.android.arouter.launcher.ARouter
import com.hand.wfive.App
import com.hand.wfive.R
import com.hand.wfive.activity.sign.SignActivity
import com.hand.wfive.ad.AdActivity
import com.hand.wfive.adapter.FileEditAdapter
import com.hand.wfive.base.Constant
import com.hand.wfive.dialog.MsgDialog
import com.hand.wfive.entity.FileEvent
import com.hand.wfive.entity.FileListModel
import com.hand.wfive.entity.FileModel
import com.hand.wfive.entity.Params
import com.hand.wfive.entity.WordImagesModel
import com.hand.wfive.loginAndVip.ApiConfig
import com.hand.wfive.loginAndVip.LoginConfig
import com.hand.wfive.loginAndVip.UserManager
import com.hand.wfive.util.FileUtils
import com.hand.wfive.util.click.singleClick
import com.hand.wfive.util.oss.OssCallBack
import com.hand.wfive.util.oss.OssRequest
import com.hand.wfive.view.dialog.DownProgressView
import com.hand.wfive.view.dialog.MoreFileCenter
import com.hand.wfive.view.dialog.MoreFileCenter.OnMoreFileCenterCallBack
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.enums.PopupAnimation
import com.rxjava.rxlife.RxLife
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.core.Observable
import io.reactivex.rxjava3.core.ObservableSource
import io.reactivex.rxjava3.schedulers.Schedulers
import kotlinx.android.synthetic.main.activity_file_edit.recycler_file
import kotlinx.android.synthetic.main.activity_file_edit.topBar
import org.greenrobot.eventbus.EventBus
import org.jetbrains.anko.find
import org.jetbrains.anko.startActivity
import rxhttp.wrapper.param.RxHttp
import rxhttp.wrapper.param.asClass
import java.io.File

class FileEditActivity : AdActivity() {
    protected lateinit var mAdapter: FileEditAdapter
    private var mPage = 1
    var fileList = ArrayList<FileModel>()

    companion object {
        fun show(context: Context) {
            context.startActivity<FileEditActivity>()
        }
    }

    override fun init() {
        fileList.clear()
        topBar.addLeftBackImageButton().singleClick { doOnBackPressed() }
        topBar.setTitle("文件中心")
//        tv_to_cloud.singleClick {
//            showNormalTip("此功能暂未开放")
//        }
//        tv_to_delete.singleClick {
//            var canDelete = false
//            for (model in fileList) {
//                if (model.select)
//                    canDelete = true
//            }
//            if (canDelete)
//                delete()
//            else
//                showNormalTip("请选择您需要删除的文件")
//        }
        mAdapter = FileEditAdapter()
        mAdapter.addChildClickViewIds(R.id.iv_more)
        mAdapter.setOnItemChildClickListener { _, view, position ->
            val model = mAdapter.getItem(position)

            XPopup.Builder(mContext)
                .dismissOnBackPressed(false).hasShadowBg(false)
                .atView(view)
                .asCustom(MoreFileCenter(mContext).addOnMoreFileCenterCallBack {
                    when (it) {
                        1 -> {
                            //签字
                            sign(model)
                        }

                        2 -> {
                            //预览
                            ARouter.getInstance()
                                .build(Constant.Path.PreviewActivity)
                                .withParcelable("model", model)
                                .navigation()
                        }

                        3 -> {
                            //保存手机
                        }

                        4 -> {
                            delete(model)
                        }
                    }

                }).show()
//            model.select = !model.select
//
        }
        mAdapter.setOnItemClickListener { _, _, position ->
            val model = mAdapter.getItem(position)
            sign(model)
        }
        recycler_file.layoutManager = LinearLayoutManager(mContext)
        (recycler_file.itemAnimator as SimpleItemAnimator).supportsChangeAnimations = false
        recycler_file.adapter = mAdapter
        mAdapter.setEmptyView(getEmptyView())

        mAdapter.loadMoreModule.isEnableLoadMore = true
        mAdapter.loadMoreModule.setOnLoadMoreListener {
            loadData()
        }

        loadData()
    }

    @SuppressLint("CheckResult")
    private fun sign(model: FileModel) {
        when (model.type) {
            Params.fileTypePdf -> {
                pdfSign(model)
            }
            Params.fileTypeWord -> {
                RxHttp.postForm(ApiConfig.getWordImageData)
                    .add("userId", UserManager.getInstance().userId)
                    .add("cloudFileId", model.id)
                    .add("appid", LoginConfig.AppId)
                    .asClass(WordImagesModel::class.java)
                    .subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe {
                        if (it.code == 200) {
                            SignActivity.show(mContext, model)
                        } else if (it.code == 203) {
                            showNormalTip("此文档正在上传，请稍后")
                        } else {
                            showNormalTip("此文档暂不可签名")
                        }

                    }

            }
            else -> {
                SignActivity.show(mContext, model)
            }
        }
    }

    private fun pdfSign(model: FileModel) {
        val suffix = model.fileId.substring(model.fileId.lastIndexOf("."))
        model.filePath = if (model.fileName.endsWith(suffix, true)) {
            "${App.getContext().cacheSignPath}/${model.fileName}"
        } else {
            "${App.getContext().cacheSignPath}/${model.fileName}${suffix}"
        }
        val file = File(model.filePath)
        if (file.exists() && FileUtils.getFileSize(file) == model.size) {
            SignActivity.show(mContext, model)
        } else {
            showLoadingTipC()
            OssRequest.getInstance().dowloadFile(
                model.fileId, model.filePath, object : OssCallBack {
                    override fun onSuccess() {
                        dismissTip()
                        SignActivity.show(mContext, model)
                    }

                    override fun onFailure(msg: String) {
                        showNormalTip(if (msg.contains("下载")) "打开失败" else msg)
                    }
                })
        }
    }

    private fun loadData() {


        RxHttp.postForm(ApiConfig.getUserFileList)
            .add("appid", LoginConfig.AppId)
            .add("userId", UserManager.getInstance().userId)
            .add("type", Params.fileTypeAll)
            .add("pageSize", 20)
            .add("page", mPage)
            .asClass<FileListModel>()
            .to(RxLife.toMain(this))
            .subscribe({
                Log.e("loadData", it.toString())
                if (it.code == ApiConfig.SUCCESSCODE) {
                    if (mPage == 1) {
                        fileList.clear()
                        fileList.addAll(it.data.records)
                        mAdapter.setNewInstance(fileList)
                    } else {
                        fileList.addAll(it.data.records)
                        mAdapter.notifyDataSetChanged()
//                        mAdapter.addData(it.data.records)
                    }
                    if (it.data.records.isEmpty()) {
                        mAdapter.loadMoreModule.loadMoreEnd()
                    } else {
                        mPage++
                        mAdapter.loadMoreModule.loadMoreComplete()
                    }
                } else resetPage()
            }, {
                resetPage()
            })
    }

    private fun getEmptyView(): View {
        val view = LayoutInflater.from(mContext)
            .inflate(R.layout.item_file_empty, recycler_file, false)
        view.find<TextView>(R.id.tv_tip).text = "暂无数据"
        return view
    }

    @SuppressLint("CheckResult")
    private fun delete(fileModel: FileModel?) {
        MsgDialog(
            mContext, "您确定删除选中文件吗？", "提示"
        ) {
            if (it == 1) {
                showLoadingTipC()
                var list = ArrayList<ObservableSource<Int>>()
                if (fileModel != null) {
                    val flatMap = Observable.just(fileModel).flatMap { vo ->
                        Observable.create<Int> { emit ->
                            OssRequest.getInstance().delCloudFile(vo, object : OssCallBack {

                                override fun onSuccess() {
                                    mAdapter.remove(vo)
                                    emit.onNext(1)
                                    emit.onComplete()

                                }

                                override fun onFailure(msg: String) {
                                    emit.onError(Throwable("删除异常"))
                                }
                            })
                        }
                    }
                    list.add(flatMap)
                } else {
                    for (model in fileList) {
                        if (model.select) {
                            val flatMap = Observable.just(model).flatMap { vo ->
                                Observable.create<Int> { emit ->
                                    OssRequest.getInstance().delCloudFile(vo, object : OssCallBack {

                                        override fun onSuccess() {
                                            mAdapter.remove(vo)
                                            emit.onNext(1)
                                            emit.onComplete()

                                        }

                                        override fun onFailure(msg: String) {
                                            emit.onError(Throwable("删除异常"))
                                        }
                                    })
                                }
                            }
                            list.add(flatMap)
                        }
                    }
                }

                Observable.ambArray(*list.toTypedArray())
                    .subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
                    .subscribe({
                        dismissTip()
                        EventBus.getDefault().post(FileEvent(Params.fileTypeAll))
                    }, {
                        dismissTip()
                        showErrorTip("删除异常")
                    })

            }
        }.show()
    }

    private fun resetPage() {
        mPage--
        if (mPage < 1) mPage = 1
        mAdapter.loadMoreModule.loadMoreComplete()
    }

    override fun getContentViewId(): Int {
        return R.layout.activity_file_edit
    }
}